//
//  LGViewController.m
//  LGBlueToothDemo1
//
//  Created by shuangwuxu on 2019/1/16.
//  Copyright © 2019年 ZnLG. All rights reserved.
//

#import "LGViewController.h"
#import <CoreBluetooth/CoreBluetooth.h>



@interface LGViewController ()<CBPeripheralManagerDelegate>
@property (strong,nonatomic) CBPeripheralManager *peripheralManager;//外围设备管理器
@property (strong,nonatomic) CBMutableCharacteristic *characteristicM;//特征
@property (strong,nonatomic) CBMutableCharacteristic *characteristicOtherM;//特征

@property (strong,nonatomic) NSMutableArray *centralMArr;//订阅此外围设备特征的中心设备

@end

@implementation LGViewController

-(NSMutableArray *)centralMArr{
    if (!_centralMArr) {
        _centralMArr = [NSMutableArray array];
    }
    return _centralMArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.title = @"外围设备";
    _peripheralManager=[[CBPeripheralManager alloc]initWithDelegate:self queue:nil];

}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.peripheralManager.delegate = nil;
    self.peripheralManager = nil;
    self.characteristicM = nil;
    [self.centralMArr removeAllObjects];
}

- (void)dealloc {
    NSLog(@"======外围设备销毁");
}

- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral{
    switch (peripheral.state) {
        case CBPeripheralManagerStatePoweredOn:
            NSLog(@"======BLE已打开.");
            //添加服务
            [self setupService];
            break;
            
        default:
            NSLog(@"此设备不支持BLE或未打开蓝牙功能，无法作为外围设备.");
            break;
    }
}
- (IBAction)updateAction:(id)sender {
    NSLog(@"======更新");
    [self updateCharacteristicValue];
}

//创建特征、服务并添加服务到外围设备
-(void)setupService{
    /*1.创建特征*/
    //创建特征的UUID对象
    CBUUID *characteristicUUID=[CBUUID UUIDWithString:kCharacteristicUUID];
    //特征值
        NSString *valueStr=kPeripheralName;
        NSData *value=[valueStr dataUsingEncoding:NSUTF8StringEncoding];
    //创建特征
    /** 参数
     * uuid:特征标识
     * properties:特征的属性，例如：可通知、可写、可读等
     * value:特征值
     * permissions:特征的权限
     */
//    CBMutableCharacteristic *characteristicM=[[CBMutableCharacteristic alloc]initWithType:characteristicUUID properties:CBCharacteristicPropertyNotify value:nil permissions:CBAttributePermissionsReadable];
    
    CBMutableCharacteristic *characteristicM=[[CBMutableCharacteristic alloc]initWithType:characteristicUUID properties:CBCharacteristicPropertyNotify|CBCharacteristicPropertyRead value:nil permissions:CBAttributePermissionsReadable];
//    characteristicM.value = value;
    self.characteristicM = characteristicM;
    
//    CBUUID *characteristicUUID2=[CBUUID UUIDWithString:kCharacteristicUUIDTWO];
//    特征值
//    CBMutableCharacteristic *characteristicM1=[[CBMutableCharacteristic alloc]initWithType:characteristicUUID2 properties:CBCharacteristicPropertyNotify value:nil permissions:CBAttributePermissionsReadEncryptionRequired];
//    self.characteristicOtherM = characteristicM1;
    
    /*创建服务并且设置特征*/
    //创建服务UUID对象
    CBUUID *serviceUUID=[CBUUID UUIDWithString:kServiceUUID];
    //创建服务
    CBMutableService *service = [[CBMutableService alloc] initWithType:serviceUUID primary:YES];
    //设置服务的特征
//    service.characteristics = @[characteristicM,characteristicM1];
    service.characteristics = @[characteristicM];

    /*将服务添加到外围设备*/
    [self.peripheralManager addService:service];

}

//添加服务开始广播
- (void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(nullable NSError *)error{
    if (!error) {//添加服务成功
        NSLog(@"======添加服务成功，%@",service);
        NSDictionary *dic=@{CBAdvertisementDataLocalNameKey:kPeripheralName};//广播设置
        [self.peripheralManager startAdvertising:dic];//开始广播
        NSLog(@"======向外围设备添加了服务并开始广播...");
    }
}

//启动广播
-(void)peripheralManagerDidStartAdvertising:(CBPeripheralManager *)peripheral error:(NSError *)error{
    if (error) {
        NSLog(@"======启动广播过程中发生错误，错误信息：%@",error.localizedDescription);
        return;
    }
    NSLog(@"======启动广播...");
}

//订阅特征
-(void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didSubscribeToCharacteristic:(CBCharacteristic *)characteristic{
    NSLog(@"======中心设备：%@ 已订阅特征：%@.",central,characteristic);
    //发现中心设备并存储
    if ([self.centralMArr containsObject:central]) {
        [self.centralMArr addObject:central];
    }
    
    /*中心设备订阅成功后外围设备可以更新特征值发送到中心设备,一旦更新特征值将会触发中心设备的代理方法：
     -(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
     */
    
    //    [self updateCharacteristicValue];
    
}

//更新特征值
-(void)updateCharacteristicValue{
    //特征值
    NSString *valueStr=[NSString stringWithFormat:@"%@ --%@",kPeripheralName,[NSDate   date]];
    NSLog(@"======更新特征值value：%@",valueStr);
    NSData *value=[valueStr dataUsingEncoding:NSUTF8StringEncoding];
    //更新特征值
    BOOL isSend = [self.peripheralManager updateValue:value forCharacteristic:self.characteristicM onSubscribedCentrals:nil];
    NSLog(@"======发送结果 %@",isSend?@"成功":@"失败");

}

- (void)peripheralManagerIsReadyToUpdateSubscribers:(CBPeripheralManager *)peripheral{
    NSLog(@"======peripheralManagerIsReadyToUpdateSubscribers");
}




- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveReadRequest:(CBATTRequest *)request
{
    NSLog(@"======didReceiveReadRequest");
//    // 查看请求的特性是否是指定的特性
//    if ([request.characteristic.UUID isEqual:self.characteristicM.UUID])
//    {
//        NSLog(@"======Request character 1");
//        // 确保读请求所请求的偏移量没有超出我们的特性的值的长度范围
//        // offset属性指定的请求所要读取值的偏移位置
//        if (request.offset > self.characteristicM.value.length)
//        {
//            [peripheral respondToRequest:request withResult:CBATTErrorInvalidOffset];
//            return;
//        }
//        // 如果读取位置未越界，则将特性中的值的指定范围赋给请求的value属性。
//        request.value = [self.characteristicM.value subdataWithRange:(NSRange){request.offset, self.characteristicM.value.length - request.offset}];
//        // 对请求作出成功响应
//        [peripheral respondToRequest:request withResult:CBATTErrorSuccess];
//    }
}

- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveWriteRequests:(NSArray *)requests
{
    NSLog(@"======didReceiveWriteRequests");

//    CBATTRequest *request = requests[0];
//    self.characteristicM.value = request.value;
//    [peripheral respondToRequest:request withResult:CBATTErrorSuccess];
}

- (void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didUnsubscribeFromCharacteristic:(CBCharacteristic *)characteristic
{
    NSLog(@"======Central subscribed to characteristic %@", characteristic);
//    NSData *updatedData = characteristic.value;
//    // 获取属性更新的值并调用以下方法将其发送到Central端
//    // 最后一个参数指定我们想将修改发送给哪个Central端，如果传nil，则会发送给所有连接的Central
//    // 将方法返回一个BOOL值，表示修改是否被成功发送，如果用于传送更新值的队列被填充满，则方法返回NO
//    BOOL didSendValue = [peripheral updateValue:updatedData forCharacteristic:(CBMutableCharacteristic *)characteristic onSubscribedCentrals:nil];
//    NSLog(@"======Send Success ? %@", (didSendValue ? @"YES" : @"NO"));
}


@end
